package com.sishu.websocket4.common;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sishu.websocket4.pojo.websocketuser;
import com.sishu.websocket4.service.impl.UserServiceimpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import javax.annotation.Resource;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.*;

@Slf4j
@Service
@ServerEndpoint("/websocketMessage")
public class MyWebSocketServer {

    @Resource
    private UserServiceimpl userService;

    // 维护一个会话集合
    private static Set<WebSocketSession> sessions = Collections.synchronizedSet(new HashSet<>());

    @OnOpen
    public void onOpen(WebSocketSession session) {
        String sessionId = session.getId();
        System.out.println("New connection: " + sessionId);
        sessions.add(session);

        // 连接成功后立即发送欢迎消息
        try {
            session.sendMessage(new TextMessage("Welcome to the WebSocket server!"));
            System.out.println("Sent welcome message to " + sessionId);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @OnMessage
    public void onMessage(TextMessage message, WebSocketSession session) {

        //获取json数组
       // AddUserMessage addUserMessage = JSONArray.parseObject(message.getPayload(), AddUserMessage.class);
        //获取json数组
        JSONArray jsonArray = JSONArray.parseArray(message.getPayload());
        //定义接受的user数组
        List<websocketuser> users = new ArrayList<>();
        String s = "";

        //循环json数组，把json数组中的元素转换成User对象
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            String userId = jsonObject.getString("userId");
            String groupId = jsonObject.getString("groupId");
            String name = jsonObject.getString("userName");
            String totalAssets = jsonObject.getString("totalAssets");
            String fluidAssets = jsonObject.getString("fluidAssets");
            String fixedAssets = jsonObject.getString("fixedAssets");

            websocketuser user = new websocketuser(userId,groupId,name,"student",totalAssets,fluidAssets,fixedAssets);
            users.add(user);
//            s = userService.insertOrUpdate(user);
        }

        //控制台打印插入数据库的结果
        System.out.println(s);

        //将对象集合转成json数组
        String jsonString = JSON.toJSONString(users);

        //把jason数组发送消息给所有客户端
        sendMessageToAll(new TextMessage(jsonString));
    }



    @OnClose
    public void onClose(Session session) {
        String sessionId = session.getId();
        System.out.println("Connection closed: " + sessionId);
        sessions.remove(session);
    }

    @OnError
    public void onError(WebSocketSession session, Throwable throwable) {

        String sessionId = session.getId();
        System.out.println("Error in session " + sessionId + ": " + throwable.getMessage());
//        sessions.remove(session);
    }

    // 发送消息给所有客户端
    public static void sendMessageToAll(TextMessage message) {
        synchronized (sessions) {

            for (WebSocketSession session : sessions) {
                if (session.isOpen()) {
                    try {
                        session.sendMessage(message
                        );
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}

//    // 发送消息给特定客户端
//    public static void sendMessageToClient(String clientId, String message) {
//        synchronized (sessions) {
//            for (Session session : sessions) {
//                if (session.getId().equals(clientId) && session.isOpen()) {
//                    try {
//                        session.getBasicRemote().sendText(message);
//                    } catch (IOException e) {
//                        e.printStackTrace();
//                    }
//                    break;
//                }
//            }
//        }
//    }
//}
